<template>
  <div>
    <div v-if="!selectedItem.type">
      <slot/>
      <!--      <h4>或</h4>-->
      <!--      <h3>点击实体/关系查看细节</h3>-->
    </div>
    <div class="maineditor" v-else>
      <!-- 编辑器头部 -->
      <div class="header">
        <div class="left">
          <el-button type="text" size="small" icon="el-icon-arrow-left" @click="selectNone">返回
          </el-button>
          <h3>{{ editorTitle }}</h3>
        </div>  
        
      </div>
      <!-- 实体编辑 -->
      <el-form
        v-if="selectedItem.type === 'node'"
        ref="editorItem"
        label-position="top"
        :rules="activeRules"
        :model="selectedItem.item"
        label-width="80px">
        <el-form-item label="实体名称" prop="name">
          <el-input
            clearable
            :disabled="!editable"
            placeholder="实体名称"
            v-model="selectedItem.item.name"></el-input>
        </el-form-item>
        <el-form-item label="实体类别" prop="group">
          <el-select
            v-model="selectedItem.item.group"
            placeholder="请选择"
            :disabled="!editable"
            @change="classicChange($event)"
            filterable
            allow-create
            style="width: 100%;">
            <el-option
              v-for="item in options.choiceClass"
              :key="item.value"
              :label="item.label"
              :value="item.value">{{item.value}}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实体权重" prop="radius">
          <el-input
            clearable
            :disabled="!editable"
            placeholder="1~20"
            v-model.number="selectedItem.item.radius"></el-input>
        </el-form-item>
        <el-form-item label="实体颜色">
          <div>
            <el-radio-group :disabled="!editable" v-model="useGroupColor">
              <el-radio :label="true" style="margin-bottom: 10px">按默认分组颜色</el-radio>
              <el-radio :label="false">自定义颜色</el-radio>
            </el-radio-group>
            <el-input
              style="padding-top: 10px"
              v-if="!useGroupColor"
              type="color"
              :disabled="!editable"
              v-model="selectedItem.item.color"></el-input>
          </div>
        </el-form-item>
        <!-- <el-form-item label="实体形状">
          <el-input
            clearable
            :disabled="!editable"
            placeholder="实体形状"
            v-model="selectedItem.item.figure"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="字体大小" prop="textSize">
          <el-input
            clearable
            :disabled="!editable"
            placeholder="单位 px"
            v-model.number="selectedItem.item.textSize"></el-input>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button id="detail" type="text" @click="showMoreDetail">属性详情</el-button>
          </div>
          <div class="properties" v-for="(prop, idx) in selectedItem.item.properties" :key="idx" >
            <div class="name">
              <el-autocomplete
                clearable
                :disabled="!editable"
                :fetch-suggestions="queryAttributes"
                placeholder="属性名"
                v-model="prop.name"
                style="width: 100%;"></el-autocomplete>
              <el-button size="small" v-if="editable" type="danger" icon="el-icon-close" 
                @click="removeProp(idx)" style="margin-left: 10px;">移除
              </el-button>
            </div>
            <el-input
              clearable
              :disabled="!editable"
              type="textarea"
              :autosize="{ maxRows: '5' }"
              placeholder="属性值"
              v-model="prop.value"
              style="margin-top: 5px;width: 100%;"></el-input>
          </div>
          <el-button size="small" v-if="editable" icon="el-icon-plus" @click="addProp" style="margin-top: 10px;">添加属性</el-button>
        </el-form-item>
        <el-form-item class="options">
          <el-button icon="elicon-document-copy" v-if="primaryButton.label==='点击修改'"  type="success" @click="copyThisNode">复制节点</el-button>
          <el-button v-if="editable" @click="alterButton.handler" >{{alterButton.label}}</el-button>
          <el-button icon="el-icon-edit" type="primary" @click="primaryButton.handler">{{primaryButton.label}}</el-button>
          <el-button v-if="!createNew && primaryButton.label==='点击修改'" style="width: 100%;" type="danger" icon="el-icon-delete" @click="deleteItem">删除{{ typeStr }}</el-button>
          <el-button  type="warning" style="width: 100%;" @click="showImportCSVDialog">{{ this.buttonName }}</el-button>
        </el-form-item>
        
      </el-form>
      <!-- 关系编辑 -->
      <el-form
        v-if="selectedItem.type === 'link'"
        ref="editorItem"
        label-position="top"
        :rules="activeRules"
        :model="selectedItem.item"
        label-width="80px">
        <el-form-item prop="name">
          <template>
            <el-row>
              <el-col :span="15">
                <p> 关系类型</p>
              </el-col>
            </el-row>
            <el-row>
              <el-autocomplete
                clearable
                :disabled="!editable"
                :fetch-suggestions="queryLinkName"
                placeholder="关系类型"
                v-model="selectedItem.item.name"
              ></el-autocomplete>
            </el-row>
          </template>
        </el-form-item>
        <el-form-item label="关系实体1" prop="from">
          <div>
            <el-select
              clearable
              :disabled="!editable"
              placeholder="实体名称"
              v-model="selectedItem.item.from"
              filterable>
              <el-option
                v-for="node in options.nodeOptions"
                :key="node.id"
                :label="node.name"
                :value="node.id" ></el-option>
            </el-select>
            <el-button
              title="点击选择目标节点"
              :disabled="!editable"
              :icon="selectingNode === 'from' ? 'el-icon-close' : 'el-icon-thumb'"
              @click="toggleSelectingNode('from')"
              @blur="toggleSelectingNode('from')"></el-button>
          </div>
        </el-form-item>
        <el-form-item label="关系实体2" prop="to">
          <div>
            <el-select
              clearable
              :disabled="!editable"
              placeholder="实体名称"
              v-model="selectedItem.item.to">
              <el-option
                v-for="node in options.nodeOptions"
                :key="node.id"
                :label="node.name"
                :value="node.id"></el-option>
            </el-select>
            <el-button
              title="点击选择目标节点"
              :disabled="!editable"
              :icon="selectingNode === 'to' ? 'el-icon-close' : 'el-icon-thumb'"
              @click="toggleSelectingNode('to')"
              @blur="toggleSelectingNode('to')"></el-button>
          </div>
        </el-form-item>
        <el-form-item label="关系权重" prop="value">
          <el-input
            clearable
            :disabled="!editable"
            placeholder="1~20"
            v-model="selectedItem.item.value"></el-input>
        </el-form-item>
        <el-form-item label="其他属性" >
          <div class="properties" v-for="(prop, idx) in selectedItem.item.properties" :key="idx">
            <div class="name">
              <el-autocomplete
                clearable
                :disabled="!editLinkName"
                :fetch-suggestions="queryAttributes"
                placeholder="属性名"
                v-model="prop.name"
                style="width: 100%;"></el-autocomplete>
              <el-button
              size="small"
                v-if="editable"
                type="danger"
                icon="el-icon-close"
                @click="removeProp(idx)" style="margin-left: 10px;">移除</el-button>
            </div>
            <el-input
              clearable
              :disabled="!editable"
              type="textarea"
              :autosize="{ maxRows: '5' }"
              placeholder="属性值"
              v-model="prop.value"
              style="width: 100%;"></el-input>
          </div>
          <el-button size="small" v-if="editable" icon="el-icon-plus" @click="addProp">添加属性</el-button>
        </el-form-item>
        <el-form-item class="options">
          
          <el-button v-if="editable" @click="alterButton.handler">{{alterButton.label}}</el-button>
          <el-button type="primary" @click="primaryButton.handler">{{primaryButton.label}}</el-button>
          <el-button type="warning" style="width: 100%;" @click="showImportCSVDialog">{{ this.buttonName }}</el-button>
        </el-form-item>
      </el-form>
      <el-dialog
        title="属性详情"
        :visible.sync="showDetail_dialog">
        <div class="properties"
          v-for="(prop, idx) in selectedItem.item.properties"
          :key="idx"
          style="display:inline-block;">
          <div class="name">
            <el-form :inline="true">
              <el-form-item :label="prop.name+': '" label-width="100px">
                <el-input
                  clearable
                  :disabled="!editable"
                  type="textarea"
                  :autosize="{ maxRows: '5' }"
                  placeholder="属性值"
                  v-model="prop.value"
                  style="width: 100%;"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div style="text-align: center;">
          <!-- <el-button v-if="" style="width: 100%;" type="warning"  icon="el-icon-folder-add" @click="showImportCSVDialog">导入CSV文件</el-button> -->
          <el-button type="primary" @click="primaryButton.handler"  >{{primaryButton.label}}</el-button>
          <!-- <el-button v-if="primaryButton.label==='点击修改'"  type="success" @click="copyThisNode">复制节点</el-button> -->
          <el-button v-if="editable" @click="alterButton.handler" style="margin-left:10%;" >{{alterButton.label}}</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title= "知识采集与智能生成"
        width="40%"
        :visible.sync="showImportCSV">
        <el-form v-loading="loading" ref="importCSV" label-width="120px">
          <el-form-item label="新增关系类型:" prop="mygroup" v-if="this.selectedItem.item.id!==undefined||this.typeStr==='关系'">
            <el-autocomplete
              clearable
              :fetch-suggestions="queryLinkName"
              placeholder="关系类型"
              v-model="formDataCSV.relationName"></el-autocomplete>
          </el-form-item>
          <el-form-item label="当前选择节点:" prop="nodeid" v-if="this.formDataCSV.nodeId!==0">
            <el-input v-model="formDataCSV.nodeId" disabled></el-input>
          </el-form-item>
          <el-form-item label="新增实体类别:" prop="nodeid" v-if="this.typeStr==='实体'">
            <el-select
              v-model="formDataCSV.group"
              placeholder="请选择"
              @change="classicChange($event)"
              filterable
              allow-create>
              <el-option
                v-for="item in options.choiceClass"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文件识别码:" prop="mygroup" v-if="this.typeStr==='实体'">
            <el-input v-model="formDataCSV.myGroup"></el-input>
          </el-form-item>
          <el-form-item label="上级节点识别码:" prop="mygroup" v-if="this.typeStr==='关系'">
            <el-input v-model="formDataCSV.fmyGroup"></el-input>
          </el-form-item>
          <el-form-item label="下级节点识别码:" prop="mygroup" v-if="this.typeStr==='关系'">
            <el-input v-model="formDataCSV.smyGroup "></el-input>
          </el-form-item>
          <el-form-item  label="上传CSV文件">
            <input type="file" id="files" ref="refFile" v-on:change="importFromCsv">
          </el-form-item>
          <el-form-item label="实体名称列:" prop="mainName" v-if="this.typeStr!=='关系'">
            <el-input v-model="formDataCSV.mainName  "></el-input>
          </el-form-item>
          <el-form-item label="关系权重:" prop="mygroup" v-if="this.typeStr==='关系'">
            <el-input v-model="formDataCSV.relationWidth" placeholder="1~20"></el-input>
          </el-form-item>
          <el-form-item v-else label="权重大小:" prop="radius">
            <el-input v-model="formDataCSV.radius" placeholder="1~20"></el-input>
          </el-form-item>
          <el-form-item label="字体大小:" prop="textSize" v-if="this.typeStr!=='关系'">
            <el-input v-model="formDataCSV.textSize" placeholder="单位为px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :offset="5" :span="4">
                <el-button @click="showImportCSV=false">取消</el-button>
              </el-col>
              <el-col :offset="1" :span="4">
                <el-button type="success" @click="submitCSV">提交</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import {mapActions} from 'vuex'
import {deepCopy} from '../../../common/utils/object';
import request from "../../../api/modules/request";
import Papa from 'papaparse'
import GraphBoard from "./GraphBoard";
import axios from 'axios'
import {updateURL,csvButton} from '../../../api/config'

export default {
  name: 'GraphEditorItem',
  props: {
    projectId: {
      type: Number
    },
    nodeOptions: {
      type: Array
    },
    nodeGroups: {
      type: Array
    }
  },
  data() {
    return {
      buttonName: csvButton,
      loading: false,
      //是否展示导入CSV弹窗
      showImportCSV: false,
      // CSV文件变量
      headersCSV: {
        'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
        'Content-Type': 'multipart/form-data'
      },
      formDataCSV: {
        nodeId: 0,
        radius: 5,
        textSize: 25,
        relationWidth: 1,
        relationName: "",
        group: ""
      },

      classicItem: {
        key: 0,
        value: ""
      },
      graphOperation: "",
      copySign: false,
      test: "111",
      info: null,
      requestGroup: [],
      currentPage: 1, //初始页
      pagesize: 5, //    每页的数据
      localProperties: {},
      editLinkName: false,


      // props: {
      //   lazy: true,
      //   lazyLoad(node, resolve) {
      //     const {level} = node
      //     let type = node.value
      //     console.log("测试数据89988：" + type)
      //     request.get('/field/knowledgeSystem/getReuse/' + 1 + "/" + 9999999 + "/" + " " + "/" + type).then(res => {
      //       const nodes = res.data.records.map(item => ({
      //         value: item.id,
      //         label: item.name,
      //         leaf: level === 1
      //       }))
      //       console.log("懒加载测试：" + JSON.stringify(nodes))
      //       resolve(nodes)
      //     })
      //   }
      // },


      choiceTest: [
        {
          value: '抽象概念',
          label: '抽象概念',
          children: []
        },
        {
          value: '实体概念',
          label: '实体概念',
          children: []
        },
        {
          value: '组件概念',
          label: '组件概念',
          children: []
        },
      ],
      btnName: '新增字段',

      useGroupColor: false,
      editable: false,
      showDetail_dialog: false,
      projectInfo: {
        id: null
      },
      selectedItem: {
        type: null,
        item: {}
      },
      originItem: null,
      options: {
        nodeOptions: [],
        nodeGroups: [],
        itemGroups: ['装备', '目标', '态势', '指控', '保障'],
        // itemGroups: [],
        linkNames: ['实例关系','组成关系', '父子关系', '属性关系'],
        nodeProperties: {
          决定点: ['名称', '经度', '纬度', '部队', '目标', '武器'],
          红方态势: ['武器装备', '作战区域', '电磁信息', '政治', '经济', '目标清单', '关键优势', '关键能力', '关键薄弱点', '关键需求', '关键因素']
        },
        linkProperties: {
          时间递进: ['时', '分', '秒'],
          态势递进: ['可跳转', '必经过']
        },
        choiceClass: [],
      },
      selectingNode: '',
      selectingMode: false,
      rules: {
        node: {
          name: [{required: true, message: '实体名称为必填项'}],
          group: [{required: true, message: '实体类别为必填项'}],
          radius: [
            {required: true, message: '实体权重为必填项'},
            {type: 'number', min: 1, message: '实体权重必须为正整数'}
          ],
          textSize: [
            {required: true, message: '字体大小为必填项'},
            {type: 'number', min: 1, message: '字体大小必须为正整数'}
          ]
        },
        link: {
          name: [{required: true, message: '关系类型为必填项'}],
          from: [{required: true, message: '关系实体1为必填项'}],
          to: [{required: true, message: '关系实体2为必填项'}],
          value: [{required: true, message: '关系权重为必填项'}]
        }
      }
    }
  },

  created() {
    if(this.selectedItem.type === 'link'){
      this.selectedItem.item.properties.push({name: '关系名称', value: ''})
      this.selectedItem.item.properties.push({name: '关系解释', value: ''})
      this.editLinkName = false
    }
    
    axios({
      methods: "get",
      url: updateURL + "/ks/knowledge-system/getReuse/" + 1 + "/" + 9999999 + "/" + "null" + "/" + "2",
      headers: {Authorization: "Bearer test1"}})
      // request.get('/admin-api/ks/knowledge-system/getReuse/' + 1 + "/" + 9999999 + "/" + "null" + "/" + "2")
      .then(res => {
        // 1:抽象 2：实体 3：组件
        // console.log("类别返回方法："+JSON.stringify(res.data.data.records))
        this.options.choiceClass = res.data.data.records.map(item => ({
          key: item.id,
          value: item.name,
        }))
        // console.log("懒加载测试：" + JSON.stringify(this.options.choiceClass ))
    })
  },


  computed: {
    typeStr() {
      return this.selectedItem.type === 'node' ? '实体' : '关系'
    },
    editorTitle() {
      return this.createNew
        ? `新增${this.typeStr}`
        : `${this.typeStr} ID: ${this.selectedItem.item.id}`
    },
    createNew() {
      return !this.selectedItem.item.id
    },
    primaryButton() {
      return !this.createNew
        ? this.editable
          ? {label: `确认修改`, handler: this.updateItem}
          : {
            label: '点击修改',
            handler: () => {
              this.editable = true
            }
          }
        : {label: `新增${this.typeStr}`, handler: this.createItem}
    },
    alterButton() {
      return this.createNew
        ? {label: '重置选项', handler: this.reset}
        : {label: '取消修改', handler: this.cancel}
    },
    // restProperties() {
    //   const {
    //     selectedItem: {
    //       type,
    //       item: { name, group, properties }
    //     },
    //     options: { nodeProperties, linkProperties }
    //   } = this
    //   const prop = type === 'node' ? group : name
    //   const props = type === 'node' ? nodeProperties : linkProperties
    //   const options = props[prop] || []
    //   const usedProperties = properties.map(prop => prop.name)
    //   const rest = options.filter(option => !usedProperties.includes(option))
    //   // console.log('restProperties', rest)
    //   return rest
    // },
    activeRules() {
      return this.rules[this.selectedItem.type]
    }
  },
  watch: {
    projectId(id) {
      this.projectInfo.id = id
    },
    useGroupColor(bool) {
      if (bool) {
        this.selectedItem.item.color = ''
      }
    },
    nodeOptions(options) {
      this.options.nodeOptions = options
    },
    nodeGroups(groups) {
      this.options.nodeGroups = groups
    },
    classicItem(item) {
      if (this.graphOperation === '新增实体') {
        axios({
          methods: "get",
          url: updateURL + `/ks/data-template/pid/${item.key}` ,
          headers: {Authorization: "Bearer test1"}}).then(res=>{
        // request.get('/field/dataTemplate/pid/' + item.key).then(res => {
          console.log("类别变化-值变了" + JSON.stringify(res.data.data))
          this.selectedItem.item.properties = res.data.data.map(d => ({
            name: d.label === null ? '' : d.label,
            value: d.value === null ? '' : d.value,
            type: d.type === null ? '' : d.type,
            map: d.map === null ? '' : d.map
          }))
          console.log("类别变化-值变了" + JSON.stringify(this.selectedItem.item.properties))
        })
      }
    }
  },
  methods: {
    ...mapActions({
      createItemAct: 'createItem',
      updateItemAct: 'updateItem',
      deleteItemAct: 'deleteItem',
      submitCSVAct: 'submitCSV'

    }),
    changeShowDetail_dialog() {
      // console.log("550Data输出测试："+JSON.stringify(this.form.fieldTemplateList))
      this.showDetail_dialog = false
    },


    /********** 外部操作事件 **********/
    //初始化项目信息
    initProjectInfo(projectInfo) {
      this.projectInfo = deepCopy(projectInfo)
    },

    createNode() {
      const newNode = this.getEditNode()
      // console.log('createNode')
      this.graphOperation = "新增实体"
      this.selectedItem.type = 'node'
      this.selectedItem.item = newNode
      console.log("新增实体测试8888：" + JSON.stringify(newNode))
      this.selectedItem.item.textSize = 25
      this.selectedItem.item.radius = 5
      this.originItem = null
      this.editable = true
      this.useGroupColor = true
      this.$emit('graph-action', 'clearFocus')
    },
    createLink() {
      const newLink = this.getEditLink()
      // console.log('createLink')
      this.selectedItem.type = 'link'
      this.selectedItem.item = newLink
      console.log("新增关系测试9999：" + JSON.stringify(newLink))
      this.selectedItem.item.value = 1
      this.originItem = null
      this.editable = true
      this.useGroupColor = true
      this.$emit('graph-action', 'clearFocus')
    },
    selectNode(node) {
      const newNode = this.getEditNode(node)
      console.log("图谱点击了节点45645678621312：" + JSON.stringify(node))
      // this.projectInfo = projectInfo
      // console.log('selectNode', newNode)
      // this.choiceTest = res.data
      this.selectedItem.type = 'node'
      this.selectedItem.item = newNode
      console.log("执行了点击节点操作8555：" + JSON.stringify(this.selectedItem.item.radius))
      this.originItem = deepCopy(newNode)
      this.editable = false
      this.useGroupColor = !node.color
    },
    selectLink(link) {
      const newLink = this.getEditLink(link)
      // console.log('selectLink', link)

      this.selectedItem.type = 'link'
      this.selectedItem.item = newLink
      console.log("******",JSON.stringify(this.selectedItem.item))
      this.originItem = deepCopy(newLink)
      this.editable = false
      this.editLinkName = false
      this.useGroupColor = true
    },
    selectNone() {
      // console.log('selectNone')
      this.selectedItem.type = ''
      this.selectedItem.item = {}
      this.$emit('graph-action', 'clearFocus')
    },
    /********** 内部方法 **********/

    classicChange(value) {
      //使用find()方法在下拉数据中根据value绑定的数据查找对象。
      // console.log("类别变化:" + JSON.stringify(this.classicItem));
      this.classicItem = this.options.choiceClass.find(function (item) {
        if (item.value === value)
          return item
      })
      // console.log("类别变化465654165:" + JSON.stringify(this.classicItem));
    },

    getEditNode(origin) {
      if (origin) {
        const {
          id,
          name,
          group,
          radius,
          color,
          figure,
          textSize,
          properties
        } = origin
        const props = []
        
        console.log("点击了节点546545：" + JSON.stringify(properties))
        for (const name in properties) {
          props.push({name, value: properties[name]})
        }
        const node = {
          id,
          name,
          group,
          radius,
          color,
          figure,
          textSize,
          properties: props
        }
        console.log("点击了节点546545：" + JSON.stringify(group))
        return node
      } else {
        return {
          name: '',
          group: '',
          radius: '',
          color: '',
          figure: '',
          textSize: 0,
          properties: []
        }
      }
    },
    getEditLink(origin) {
      if (origin) {
        const {id, name, from, to, value, properties} = origin
        const props = []
        
        for (const name in properties) {
          props.push({name, value: properties[name]})
        }
        const newLink = {id, name, from, to, value, properties: props}
        console.log('newLink',newLink)
        return newLink
      } else {
        const properties = []
        properties['关系名称'] = ''
        properties['关系解释'] = ''
        const props = []
        for (const name in properties) {
          props.push({name, value: properties[name]})
        }
        return {
          name: '',
          from: '',
          to: '',
          value: '',
          properties: props
        }
      }
    },
    // 添加实体/关系属性
    addProp() {
      // console.log('关系属性this.selectedItem.item.properties***********',this.selectedItem.item.properties)
      // if(this.selectedItem.type ==='link' && this.selectedItem.item.properties.length === 0){
      //   // 添加默认的关系属性
      //   this.selectedItem.item.properties.push({name: '关系名称', value: ''})
      //   this.selectedItem.item.properties.push({name: '关系解释', value: ''})
      //   this.editLinkName = false
      // }
      // else{
      //   console.log('***********')
        this.selectedItem.item.properties.push({name: '', value: ''})
        this.editLinkName = true
      // }
      
    },
    // 删除实体属性
    removeProp(idx) {
      this.selectedItem.item.properties.splice(idx, 1)
    },
    toggleSelectingNode(attr) {
      const mode = this.selectingNode !== attr
      const node = mode ? attr : ''
      this.selectingMode = mode
      this.selectingNode = node
      this.$emit('graph-action', 'setSelectingMode', mode)
    },
    catchNode(node) {
      const {id, name} = node
      console.log("项目id456456：" + JSON.stringify(this.projectInfo))
      // console.log(`catchNode: id=${id}, name=${name}`)
      this.selectedItem.item[this.selectingNode] = node.id
      this.selectingMode = false
      this.selectingNode = ''
      console.log("编辑页面收到的数据："+JSON.stringify(this.selectedItem.item))
    },
    // 重置选项
    reset() {
      const item = this.selectedItem.item
      for (const prop in item) {
        item[prop] = ''
      }
    },
    // 重置属性
    cancel() {
      this.editable = false
      this.editLinkName = false
      // reset attribute
      this.selectedItem.item = deepCopy(this.originItem)
    },
    validate() {
      return new Promise(resolve => {
        this.$refs.editorItem.validate(res => {
          resolve(res)
        })
      })
    },
    async createItem() {
      const {
        projectInfo: {id: projectId},
        selectedItem: {type, item},
        validate,
        copySign
      } = this
      console.log("执行了创建节点的操作" + JSON.stringify(item))
      const res = await validate()
      // console.log('validate', res)
      if (!res) return
      console.log(item)
      // item.group = JSON.stringify(item.group)
      // console.log("数据测试111:" + JSON.stringify(projectId))
      // console.log("数据测试111:" + JSON.stringify(type))
      // console.log("数据测试111:" + JSON.stringify(item))
      // console.log("数据测试111:" + JSON.stringify(copySign))
      this.createItemAct({projectId, type, item, copySign}).then(item => {
        console.log("复制了节点：" + JSON.stringify(item))
        if (item) {
          if (type === 'node') {
            this.$emit('graph-action', 'createNode', item)
            this.selectNode(item)
          } else if (type === 'link') {
            this.$emit('graph-action', 'createLink', item)
            this.selectLink(item)
          }
        }
      })
    },
    async updateItem() {
      const {
        projectInfo: {id: projectId},
        selectedItem: {type, item},
        validate
      } = this
      const res = await validate()
      // console.log('validate', res)
      if (!res) return
      console.log("修改item546456：" + JSON.stringify(this.projectInfo))
      //item的group属性为[名称,编号]——数组
      // item.group = item.group[0]
      // console.log("修改item：222  " + JSON.stringify(item))
      console.log("数据测试222:" + JSON.stringify(projectId))
      console.log("数据测试222:" + JSON.stringify(type))
      console.log("数据测试222:" + JSON.stringify(item))
      // console.log("数据测试111:" + JSON.stringify(copySign))

      this.updateItemAct({projectId, type, item}).then(item => {
        if (item) {
          if (type === 'node') {
            this.$emit('graph-action', 'updateNode', item)
            this.selectNode(item)
          } else if (type === 'link') {
            this.$emit('graph-action', 'updateLink', item)
            console.log("数据测试333:" + JSON.stringify(item))
            this.selectLink(item)
          }
        }
      })
    },
    deleteItem() {
      const {
        projectInfo: {id: projectId},
        selectedItem: {type, item}
      } = this
      this.deleteItemAct({projectId, type, id: item.id}).then(res => {
        if (res) {
          const action =
            type === 'node' ? 'deleteNode' : type === 'link' ? 'deleteLink' : ''
          if (action) {
            this.$emit('graph-action', action, item.id)
            this.selectNone()
          }
        }
      })
    },

    // showMoreDetail(){
    //   this.showDetail_dialog=true
    //   console.log("条件检测546："+ JSON.stringify(this.selectedItem.item.properties))
    //   if(this.selectedItem.item.properties.length>0){
    //     console.log("条件检测546执行了if")
    //     this.form.fieldTemplateList = this.selectedItem
    //   }else{
    //     console.log("条件检测546执行了else")
    //     axios({
    //       methods: "get",
    //       url: updateURL + "/field/data-template/" +this.selectedItem.item.group,
    //       headers: {Authorization: "Bearer test1"}}).then(res=>{
    //     // request.get(updateURL+"/field/data-template/"+this.selectedItem.item.group).then(res=>{
    //       // const middltest = JSON.parse(res.data[0].template)
    //       this.form.fieldTemplateList = JSON.parse(res.data[0].template)
    //       // this.form.fieldTemplateList.forEach(d=>{
    //       //   d.field_value = ""
    //       //   d.label_value = ""
    //       // })
    //       console.log("接口返回测试zxc："+JSON.stringify(this.form.fieldTemplateList))
    //       // console.log("请求测试xzcsa："+JSON.stringify(res.data[0].template))
    //     })
    //   }
    // },

    showMoreDetail() {
      this.showDetail_dialog = true
      console.log("获取模板测试454：" + JSON.stringify(this.selectedItem.item.group.key))
      axios({
          methods: "get",
          url: updateURL + `/ks/data-template/pid/${this.selectedItem.item.group.key}` ,
          headers: {Authorization: "Bearer test1"}}).then(res=>{
      // request.get("/field/dataTemplate/getNameTemplate/" + this.selectedItem.item.group).then(res => {
        // const middltest = JSON.parse(res.data[0].template)
        this.form.fieldTemplateList = JSON.parse(res.data[0].template)
        // this.form.fieldTemplateList.forEach(d=>{
        //   d.field_value = ""
        //   d.label_value = ""
        // })
        this.form.fieldTemplateList.forEach(itemD => {
          itemD.value = this.selectedItem.item.properties.find(select => select.name === itemD.field).value
        })
        // console.log("赋值测试xcvojada："+JSON.stringify(this.form.fieldTemplateList))
        // console.log("接口返回测试zxc：" + JSON.stringify(this.selectedItem.item.properties))
        // console.log("请求测试xzcsa："+JSON.stringify(res.data[0].template))
      })
    },
    queryGroup(_, cb) {
      axios({
          methods: "get",
          url: updateURL + "/ks/data-template/getName",
          headers: {Authorization: "Bearer test1"}}).then(res=>{
      // request.get("/field/dataTemplate/getName").then(res => {
        var middleName
        // console.log("请求测试：" + JSON.stringify(res))
        res.data.forEach(d => {
          if (d) {
            if (!this.requestGroup.includes(d.name))
              this.requestGroup.push(d.name)
          }
        })
        this.options.itemGroups = this.requestGroup
        return cb(this.options.itemGroups.map(group => ({value: group})))
      })
    },
    queryLinkName(_, cb) {
      // console.log(类型测试："+JSON.stringify(this.options.linkNames))
      return cb(this.options.linkNames.map(name => ({value: name})))
    },
    queryAttributes(_, cb) {
      const {
        selectedItem: {
          type,
          item: {name, group}
        },
        options: {nodeProperties, linkProperties}
      } = this
      const prop = type === 'node' ? group : name
      const props = type === 'node' ? nodeProperties : linkProperties
      const suggestions = props[prop] || []
      return cb(suggestions.map(option => ({value: option})))
    },
    getValueByName(name) {
      this.localProperties.forEach(d => {
        if (d.name === name) {
          console.log("传输测试zxczvege:" + JSON.stringify(d))
          return d
        }
      })

      return " "
    },
    handleSizeChange(size) {
      // console.log(size,'size');
      this.pagesize = size;
      // console.log(this.pagesize); //每页下拉显示数据
    },
    handleCurrentChange(currentPage) {
      // console.log(currentPage,'currentPage');
      this.currentPage = currentPage;
      // console.log(this.currentPage); //点击第几页
    },
    onInput() {
      this.$forceUpdate();
    },
    copyThisNode() {
      console.log("执行了复制节点的操作：")
      this.copySign = true
      this.createItem()
    },
    change(e) {
      let nodeObj = this.$refs["cascader"].getCheckedNodes()
      console.log("节点的值", e)

      console.log("节点全部数据", nodeObj)
    },

    //上传CSV文件方法
    handleSuccess(response, file, fileList) {
      console.log(response);
    },
    handleError(err, file, fileList) {
      console.log(err);
    },
    beforeUpload(file) {
      this.formData = new FormData();
      this.formData.append('file', file);
    },
    //CSV文件导入处理方法
    importFromCsv() {
      
      let selectedFile = null
      selectedFile = this.$refs.refFile.files[0];
      if (selectedFile === undefined) {
        return
      }
      var reader = new FileReader();
      reader.readAsDataURL(selectedFile);
      reader.onload = evt => {
        // 检查编码
        let encoding = this.checkEncoding(evt.target.result);
        // 将csv转换成二维数组
        Papa.parse(selectedFile, {
          encoding: encoding,
          complete: res => {
            // UTF8 \r\n与\n混用时有可能会出问题
            let data = res.data;
            if (data[data.length - 1] == "") {
              //去除最后的空行
              data.pop();
            }
            console.log("csv文件导入" + JSON.stringify(data));
            let otherColumn = data.splice(1, data.length - 1)
            // data就是文件里面的数据
          }
        });
      };
      
    },
    
    
    //格式检验
    checkEncoding(base64Str) {
      // 这种方式得到的是一种二进制串
      var str = atob(base64Str.split(';base64,')[1])
      // console.log(str);
      // 要用二进制格式
      const jschardet = require("jschardet");
      var encoding = jschardet.detect(str)
      encoding = encoding.encoding
      // console.log( encoding );
      if (encoding === 'windows-1252') {	// 有时会识别错误（如UTF8的中文二字）
        encoding = 'ANSI'
      }
      return encoding
    },
    submitCSV() {
      this.loading = true;
      const {
        projectInfo: {id: projectId},
        formDataCSV
      } = this
      // formDataCSV.mygroup = parseInt(formDataCSV.mygroup)
      formDataCSV.file = this.$refs.refFile.files[0]
      formDataCSV.projectId = projectId
      console.log("提交信息预览：" + JSON.stringify(formDataCSV))
      if(this.typeStr==='关系'){//新增关系时提交接口
        formDataCSV.signNodeRelation = false
      }else{//新增节点时提交接口
        formDataCSV.signNodeRelation = true
      }
      this.submitCSVAct(formDataCSV).then(item => {
       
        this.loading = false;
        // setTimeout(() => {
        //   this.loading = false;
        // }, 1000);
        console.log("复制了节点：" + JSON.stringify(item))
        if (item) {
          this.showImportCSV = false
          this.updateItem()
          //引入刷新文件的方法
          this.selectNone()
          
          this.$router.push('/')
          setTimeout(() => {
            this.$router.push(`/graph/${projectId}`)
          }, 1)
          
          // this.selectedItem(this.selectedItem.item)
          // this.$emit('graph-action','updateData');
          // if (type === 'node') {
          //   this.$emit('graph-action', 'createNode', item)
          //   this.selectNode(item)
          // } else if (type === 'link') {
          //   this.$emit('graph-action', 'createLink', item)
          //   this.selectLink(item)
          // }
        }
        
      })
      
    },
    showImportCSVDialog() {
      this.showImportCSV = true
      this.formDataCSV = {
        group:"",
        myGroup:"",
        fmyGroup:"",
        smyGroup:"",
        mainName:"",
        nodeId: 0,
        radius: 5,
        textSize: 25,
        relationWidth: 1,
        relationName: ""
      }
      console.log("this.selectedItem.item.id：" + this.selectedItem.item.id)
      this.formDataCSV.nodeId = this.selectedItem.item.id === undefined ? 0 : this.selectedItem.item.id
    },
  },

}
</script>

<style scoped>
.maineditor .header {
  /* display: flex; */
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  
}

.maineditor .header > .left {
  gap: 16px;
}
.buttonop{
  margin-bottom: 10px;
}

.maineditor .el-form-item {
    margin-bottom: 15px;
}
::v-deep .el-form--label-top .el-form-item__label{
  padding-bottom: 0px;
}

.properties {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}

.properties > .name {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding-bottom: 3px;
}

.properties + .properties {
  margin-top: 10px;
}

.options .el-button{
  margin: auto;
  margin-right: 2%;
  margin-bottom: 10px;
width: 47%;
}


</style>
